﻿using System;
using System.Management.Automation;
using System.Linq;
using System.Collections.Generic;

namespace LinqToPowershell
{
    /// <summary>
    /// Base class for cmdlets that operate on a piped-in QueryWrapper
    /// </summary>
    public abstract class LazyCmdlet : PSCmdlet
    {        
        [Parameter(Mandatory = true, ValueFromPipeline = true)]
        public QueryableWrapper Input { get; set; }

        protected override void ProcessRecord()
        {
            QueryableWrapper result = Process();

            bool executeNow;
            if (_shouldExecute.HasValue)
                executeNow = _shouldExecute.Value;
            else
                executeNow = MyInvocation.PipelinePosition == MyInvocation.PipelineLength;

            if (executeNow)
                WriteObject(result.Query);
            else
                WriteObject(result);
        }

        protected virtual QueryableWrapper Process()
        {
            return Input;
        }
        
        protected bool? _shouldExecute = null;    
    }
}
